package com.hb.trade.api.routine.service.login;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.hb.core.pojo.JSONObjectProperty;
import com.hb.core.pojo.UserConfig;
import com.hb.core.pojo.center.au.dto.RoleDTO;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.enums.RoleTypeEnum;
import com.hb.trade.client.center.RoleClient;
import com.hb.trade.client.center.UserClient;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.user.login.SimpleUserExample;
import org.fzzn.core.util.Enums;
import org.fzzn.core.web.util.SpringUtils;

import java.util.List;

/**
 * 交易平台用户登录之后构建角色等授权信息
 *
 * @autho zhaojk
 */
public class TradeCollectUserInfo implements CollectUserInfo {
    /**
     * 构建用户的数据权限, 登录权限, 角色权限
     *
     * @param user 登录用户信息
     */
    @Override
    public void collectInfo(SimpleUserExample user) {
        Long userId = user.getId();
        User userParam = new User();
        userParam.setId(userId);

        // 查询用户的角色信息
        RoleClient roleClient = SpringUtils.getBean(RoleClient.class);
        Message<List<RoleDTO>> rolesMsg = roleClient.listRolesByUser(userParam);

        // 扩展信息
        JSONObject extInfo = user.getExtInfo();

        // 设置角色信息
        if (rolesMsg.isSuccess()) {
            List<RoleDTO> data = rolesMsg.getData();
            RoleDTO unCheckRole = CollUtil.findOne(data, item -> Enums.equals(RoleTypeEnum.UN_CHECKED_AGENCY, item.getRoleType()));
            if (unCheckRole != null) {
                // 设置一个未审核角色返回
                extInfo.set("roleType", unCheckRole.getRoleType());
            }

            // 业务角色
            RoleDTO roleSignRole = CollUtil.findOne(data, item -> item.getRoleSign() != null);
            if (roleSignRole != null) {
                extInfo.set("roleSign", roleSignRole.getRoleSign());
            }

            RoleDTO max = CollUtil.max(data);
            extInfo.set("roleDataAuth", max.getRoleDataAuth());
        }

        // 查询用户信息
        UserClient userClient = SpringUtils.getBean(UserClient.class);
        Message<User> userMsg = userClient.getByUserId(userId);
        if (userMsg.isSuccess()) {
            userParam = userMsg.getData();
            extInfo.set("userStatus", userParam.getUserStatus());
            extInfo.set("accountLevel", userParam.getAccountLevel());
            UserConfig userConfig = userParam.getUserConfig();
            if (userConfig != null) {
                extInfo.set("canCreateBranchCompany", userConfig.getCanCreateBranchCompany());
            }
        }
        user.setExtInfo(extInfo);
    }
}
